package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    public static final String SQLTYPE_SELECT = "select";
    public static final String SQLTYPE_INSERT = "insert";
    public static final String SQLTYPE_UPDATE = "update";
    public static final String SQLTYPE_DELETE = "delete";

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parseSingleMapper(InputStream inputStream) throws Exception {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();

        String namespace = rootElement.attributeValue("namespace");
        String[] sqlTypes = new String[] { SQLTYPE_SELECT, SQLTYPE_INSERT, SQLTYPE_UPDATE, SQLTYPE_DELETE };

        for (String sqlType : sqlTypes) {
            // List<Element> list = rootElement.elements("//select");
            List<Element> list = rootElement.selectNodes("//" + sqlType);
            putMappedStatement(list, sqlType, namespace);
        }
    }

    private void putMappedStatement(List<Element> list, String sqlType, String namespace) {

        MappedStatement mappedStatement;
        String key;
        for (Element element : list) {
            mappedStatement = new MappedStatement();
            mappedStatement.setId(element.attributeValue("id"));
            mappedStatement.setSqlType(sqlType);
            mappedStatement.setResultType(element.attributeValue("resultType"));
            mappedStatement.setParameterType(element.attributeValue("parameterType"));
            mappedStatement.setSql(element.getTextTrim());

            key = namespace + "." + element.attributeValue("id");
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }
}
